<?php

namespace app\models\system;

use app\models\City;
use Yii;

/**
 * This is the model class for table "set_express_city".
 *
 * @property int $id
 * @property string|null $province 省id
 */
class SetExpressCity extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'set_express_city';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['province'], 'string'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'province' => 'Province',
        ];
    }

    public static function getLastOne()
    {
        $model = self::find()
            ->orderBy(['id' => SORT_DESC])
            ->one();

        if (!$model) {
            $model = new self();
        }

        // province
        if ($model->province) {
            $province = explode(',', $model->province);
            if (count($province)) {
                $model->province = $province;
            } else {
                $model->province = [];
            }
        }

        return $model;
    }

    public static function saveData($data)
    {
        $model = self::getLastOne();
        if ($data) {
            $list = implode(',', $data);
            $model->province = $list;
        } else {
            $model->province = '';
        }

        return $model->save();
    }

    public static function getName()
    {
        $model = self::getLastOne();

        if ($model->province) {
            $list = [];
            foreach ($model->province as $id) {
                $list[] = City::find()
                    ->where(['id' => $id])
                    ->select(['name'])
                    ->scalar();
            }
            return $list;
        }

        return [];
    }
}
